package xyz.cerberu.cet.spider.resource.spider.Logic;


import com.spider.core.ProcessLogic;
import com.spider.page.HtmlPage;
import com.spider.page.ResultPage;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import xyz.cerberu.cet.anime.dao.AnimeDao;
import xyz.cerberu.cet.anime.domain.Anime;
import xyz.cerberu.cet.resource.dao.ResourceDao;
import xyz.cerberu.cet.resource.domian.Resource;
import xyz.cerberu.cet.search.dao.SearchDao;
import xyz.cerberu.cet.subtitle.dao.SubtitleDao;
import xyz.cerberu.cet.subtitle.domain.Subtitle;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author β世界
 * Created on 15:41
 * @Description 动漫资源的爬取逻辑
 */
@Component
public class ResourceLogic implements ProcessLogic {
    private static final Logger logger = LoggerFactory.getLogger(ResourceLogic.class);

    private final AnimeDao animeDao;
    private final SubtitleDao subtitleDao;
    private final ResourceDao resourceDao;
    private final SearchDao searchDao;

    private static final String PAGE_XPATH = "//*[@id=\"1280_ad\"]/div[3]/div[2]/div/a";
    private static final String RESOURCES_XPATH = "//*[@id=\"topic_list\"]/tbody/tr";

    @Autowired
    public ResourceLogic(AnimeDao animeDao, SubtitleDao subtitleDao, ResourceDao resourceDao, SearchDao searchDao) {
        this.animeDao = animeDao;
        this.subtitleDao = subtitleDao;
        this.resourceDao = resourceDao;
        this.searchDao = searchDao;
    }

    @Override
    public boolean isProcess(ResultPage resultPage) {
        return true;
    }

    @Override
    public void logic(ResultPage resultPage) {
        HtmlPage page = (HtmlPage) resultPage;
        // 下一页
        List<Element> nextPage = page.xpath(PAGE_XPATH);
        for (Element value : nextPage) {
            if ("下一頁".equals(value.text())) {
                page.addUntreated(page.insertDomain(value.attr("href")));
            }
        }

        // 获取到的所有资源链接
        List<Element> elements = page.xpath(RESOURCES_XPATH);

        // 获取动漫的名字
        String animeName;
        String aniId = null;
        try {
            String url = page.getUrl().toString();
            animeName = URLDecoder.decode(url.substring(url.indexOf("=")+1,url.indexOf("&")),"utf-8");
            if(animeName != null && !"".equals(animeName)){
                // 动漫对象
                List<Anime> anime = searchDao.selectFuzzyAnimeByName(animeName);
                if(anime.size() != 0){
                    aniId = anime.get(0).getAni_id();
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 循环遍历每个资源链接
        for (Element element : elements) {
            // 资源对象
            Resource resource;

            // 获取更新时间
            String updateTime = element.selectFirst("span[style=display: none;]").text();
            // 标题
            String title = element.select("a[target=_blank]").text();
            // 磁力
            String magnetUrl = element.getAllElements().select("a[title=磁力下載]").attr("href");
            // 字幕组名
            String subtitleName = element.select("span[class=tag]").text();
            // 获取这个字幕组的信息
            Subtitle subtitle;
            if (!"".equals(subtitleName.trim())) {
                subtitle = subtitleDao.selectSubtitle(subtitleName);
                if(subtitle == null){
                    subtitleDao.subtitleInsert(subtitleName);
                    logger.info("添加了一个新的字幕组:" + subtitleName);
                    subtitle = subtitleDao.selectSubtitle(subtitleName);
                }
            } else {
                subtitle = subtitleDao.selectBySub_id(1);
            }
            // 创建资源对象
            resource = new Resource(null,aniId,subtitle,title,magnetUrl,updateTime);
            resource.setRes_id();

            // 判断是否该插入这条数据
            if(aniId != null && !"".equals(aniId.trim())){
                // 判断更新的时间
                if(updateTimeCheck(updateTime,aniId)){
                    try {
                        resourceDao.insertResource(resource);
                        logger.info("添加资源："+resource.getResource_title()+" 更新时间："+resource.getUpdate_time());
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.info(page.getUrl() + "-内容异常：" + e);
                    }
                }
            }else{
                resourceDao.insertResource(resource);
            }
        }
    }

    /**
     * @author β世界 on 16:24 2020/4/12
     * @Description 更新时间检查
     * 若一条资源的更新时间小于这个动漫的更新时间那么就认为这个资源不是和这个动漫同一个季度的
     * 为了防止一个动漫的名字在以前有重合的问题，采取的时间判断(动漫开更的当天，一直到4个月后的更新，都算有效资源)
     * 当这个动漫是存储在长期的列表中的时候，默认允许添加所有时间段的动漫 （例如：海贼王）
     * @param updateTime:资源的更新时间
	 * @param aniId:动漫的id
     * @return boolean
     **/
    private boolean updateTimeCheck(String updateTime,String aniId){
        Date resourceUpdate = null;
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm");
            resourceUpdate = dateFormat.parse(updateTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Anime anime = animeDao.selectAnimeByID(aniId);
        Date animeTime = anime.getUpdate_Time();

        // 检查资源的更新时间是否大于动漫的更新时间
        // 需要有一个稳定的区间，至少要有4个月的区间(方便动漫)
        return resourceUpdate != null && animeTime.getTime() <= resourceUpdate.getTime();

    }

}
